/**
 * 小区回填列表
 */

$(function(){
	/*绑定全选事件*/
	bindingSelectAll('popCommunity2ListTableDiv');
	//实现回填列表数据搜索
	$('div span.btn_search').click(function(){
		var data =communityList.data;
		data.name = $('#hidden_name').val();
		getPopTablePageData(data);
	});
	
	//实现分页条件查询
	console.log('popCommunity2ListTableDiv');
	$('#popCommunity2ListTableDiv div.my-pagination > div > a').click(function(){
		var data = communityList.data;
		data.name = $('#hidden_name').val();
		var href = $(this).attr('href');
		//截取href中#之后的值
		var str = href.substring(1,href.Length);
		data.page=parseInt(str);
		getPopTablePageData(data);
	});
	$('#popCommunity2ListTableDiv div.my-pagination .page-current').change(function(){
		var data =communityList.data;
		data.name = $('#hidden_name').val();
		var page = $(this).val();
		data.page=parseInt(page);
		getPopTablePageData(data);
	});
	adjustTableCellWidth('popCommunity2ListTableDiv');
});

function getPopTablePageData(data){
	doDataPost(data, false, ctx+"/common/community/backfill2", function(msg){
		$($('.layui-layer-content')[0]).empty();
		$($('.layui-layer-content')[0]).append(msg);
		layer.iframeAuto(indexLayer);
		checkedboxInpage(commIds);
	});
}

/***********************************checkbox相关内容开始***************************************/

var backfillcheckbox=$("table.community_backfill2").find(':input[type=checkbox]');
//点击小区全选按钮 
$('#popCheckbox').click(function(){
	console.log('popCheckbox');
	var hasNoChecked = false; //是否有没有选择上的
	for(var i=0; i<backfillcheckbox.length; i++){
		if(!backfillcheckbox[i].checked){
			hasNoChecked = true;
			break;
		}
	}
	
	backfillcheckbox.each(function () {
		if(hasNoChecked){
	        if(!this.checked){//把所有未选中的全部选中，并触发change
	        	 this.checked = "checked"; 
	        	 $(this).change();
	        }
		}else{
			this.checked = !this.checked;
	        $(this).change();
		}
     });
});
//点击小区选择确定按钮 
$('#btn_commSelected').click(function(){
	var data = {};
	data.communityIds = commIds;
	data.communityNames = commNames;
	communityList.backfillFun(data);
	layer.closeAll();
});

//监听小区复选框选中状态
backfillcheckbox.change(function(){
	var commid=$(this).val();
	var commName=$(this).parents("tr").children("td").eq(1).html();

	//先删除一次 避免重复添加到数组
	commIds.remove(commid);
	commNames.remove(commName);
	//如果选中，添加到数组
	if(this.checked){
		commIds.push(commid);
		commNames.push(commName);
	} 
	$("#selectedComms").val(commNames);
});

//检查默认选中该页已经勾选过的复选框。适用于翻页情况
function checkedboxInpage(){
	$("#selectedComms").val(commNames);
	backfillcheckbox.each(function () {
		for (var i = 0; i < commIds.length; i++) {
			if (commIds[i] ==$(this).val())
				this.checked = "checked";
		}
     });
}

//获取数组元素下标
Array.prototype.indexOf = function(val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val) return i;
	}
	return -1;
};
//移除数组元素
Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
	if (index > -1) 
		this.splice(index, 1);

};